package cn.com.aiouyi.entity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.persistence.AttributeConverter;
import javax.persistence.Column;
import javax.persistence.Convert;
import javax.persistence.Converter;
import javax.persistence.Entity;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Transient;

import org.apache.commons.lang3.StringUtils;

import cn.com.aiouyi.common.BaseAttributeConverter;
import cn.com.aiouyi.vo.Link;
import lombok.Getter;
import lombok.Setter;

/**
 * Entity - 导航
 * @author hanson
 *
 */
@Getter
@Setter
@Entity
@Table(name = "t_navigation")
public class Navigation extends SeqEntity<Long>{

	private static final long serialVersionUID = 1L;

	/** 树路径分隔符 */
	public static final String TREE_PATH_SEPARATOR = ",";
	
	/** 标题 */
	private String title;
	
	/** 是否显示，默认true */
	private Boolean isDisplay = true;
	
	/** 是否新窗口打开，默认true  */
	private Boolean isOpenNew = true;
	
	/** 链接对象 */
	@Column(length = 4000)
	@Convert(converter = LinkConverter.class)
	private Link link;
	
	/** 导航位 */
	@ManyToOne
	private NavigationPosition navigationPosition;
	
	/** 树路径 */
	private String treePath;

	/** 层级 */
	private Integer grade;
	
	/** 父级 */
	@ManyToOne
	private Navigation parent;
	
	/** 子级 */
	@OneToMany(mappedBy="parent")
	private List<Navigation> children = new ArrayList<>();
	
	/**
	 * 获取所有上级ID
	 * @return 所有上级ID
	 */
	@Transient
	public Long[] getParentIds() {
		String[] parentIds = StringUtils.split(getTreePath(), TREE_PATH_SEPARATOR);
		Long[] result = new Long[parentIds.length];
		for (int i = 0; i < parentIds.length; i++) {
			result[i] = Long.valueOf(parentIds[i]);
		}
		return result;
	}
	
	/**
	 * 临时的存数据的变量，便于往模板中加载其它数据
	 */
	@Transient
	private Map<String, Object> temp = new HashMap<String, Object>();

	/**
	 * 获取临时数据
	 * @return
	 */
	@Transient
	public Map<String, Object> getTemp() {
		return temp;
	}

	/**
	 * 设置临时数据
	 * @param temp
	 */
	@Transient
	public void setTemp(Map<String, Object> temp) {
		this.temp = temp;
	}
	
	/**
	 * 类型转换 - 链接对象
	 */
	@Converter
	public static class LinkConverter extends BaseAttributeConverter<Link> implements AttributeConverter<Object, String> {
	}
}
